package com.creating.mict.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.creating.mict.common.DateUtils;
import com.creating.mict.domain.PatientRule;
import com.creating.mict.domain.PatientSetting;
import com.creating.mict.domain.XtyRecord;
import com.creating.mict.domain.XyjRecord;


/** 
 * @ClassName: XyjDao 
 * @Description: 血压计模块Dao
 * @author xuelei
 * @date 2012-3-9 下午7:53:55 
 *  
 */
public class XyjDao extends HibernateDaoSupport {

private static final Log log = LogFactory.getLog(XyjDao.class);
	
	
	/**
	 * 
	* @Title: queryPatientXyj 
	* @Description: 获取血压计签约患者及其测量结果
	* @param @param fbtime
	* @param @param fetime
	* @param @param fstate
	* @param @param fkeywords
	* @param @return 
	* @return List<Patient>    返回类型 
	* @throws
	 */
public List<XyjRecord> queryPatientXyj(String loginName, String foffice, String fbtime, String fetime, String fstate, String fkeywords, String ftakeBack) {
		
		String sql = "";
		sql = " select a.fpid, a.fname, a.fsex, a.fphone1, a.fstate, b.fssy, b.fszy, b.fxl, b.fdate, b.frdate, b.fstate_data "
			+ " , c.fssy_high, c.fssy_low, c.fszy_high, c.fszy_low, c.fmyc_high, c.fmyc_low, c.fxl_high, c.fxl_low "
			+ " from tds_patient a, tds_xyj_record b, tds_patient_setting c " 
			+ " where a.fphone1=b.fphone and a.fphone1=c.fphone "; 
		
		if(fbtime == null || fbtime.equals("null") || fbtime.equals("")) {
			sql += " and b.frdate <= to_date('" + fetime + " 23:59:59','yyyy-mm-dd hh24:mi:ss') ";
		} else {
			sql += " and b.frdate between to_date('" + fbtime + " 00:00:00','yyyy-mm-dd hh24:mi:ss') and to_date('" + fetime + " 23:59:59','yyyy-mm-dd hh24:mi:ss') ";
		}
		
		//分中心查询
		if(loginName.equals("admin")) {
			//do nothing
		} else {
			sql	+= " and a.foffice='" + foffice + "' ";
		}
		
		
		if(fstate.equals("0")) {
			sql	+= " "; 
		} else {
			sql	+= " and b.fstate_data='" + fstate + "' ";
		}
		
		if(fkeywords == null || fkeywords.equals("null")) {
			//do nothing
		} else {
			sql	+= " and (a.fname like '" + fkeywords + "%' or a.fname_pym like '" + fkeywords + "%' "
				 + " or a.fybkh like '" + fkeywords + "%' "
				 + " or a.fphone1 like '" + fkeywords + "%') ";
		}
		
		//获取当前机构所有人的检测值
		if(ftakeBack != null && (ftakeBack.equals("true") || ftakeBack.equals("1"))) { //取反
			
		//获取当前机构自己签约患者的检测值
		} else {
			if(loginName.equals("admin")) {
				//do nothing
			} else {
				sql	+= " and a.FSIGN_DOCTOR='" + loginName + "' ";
			}
		}
		
		sql	+= " order by b.frdate desc, a.fname asc ";
		
		Query query = this.getSession().createSQLQuery(sql);
		List list = query.list();
		List<XyjRecord> xr_list = new ArrayList<XyjRecord>();
		
		String ssy1 = "";
		String ssy2 = "";
		String szy1 = "";
		String szy2 = "";
		String myc1 = "";
		String myc2 = "";
		String xl1 = "";
		String xl2 = "";
		
		
		for (int i = 0; i < list.size(); i++) {
			Object[] obj = (Object[]) list.get(i);
			XyjRecord xr = new XyjRecord();
			for (int j = 0; j < obj.length; j++) {
				xr.setFpid("" + obj[0]);
				xr.setFname("" + obj[1]);
				xr.setFsex("" + obj[2]);
				xr.setFphone("" + obj[3]);
				xr.setFstate("" + obj[4]);
				xr.setFssy("" + obj[5]);
				xr.setFszy("" + obj[6]);
				xr.setFxl("" + obj[7]);
				xr.setFdateStr("" + obj[8]);
				xr.setFrdateStr("" + obj[9]);
				
				ssy1 = "" + obj[11];
				ssy2 = "" + obj[12];
				szy1 = "" + obj[13];
				szy2 = "" + obj[14];
				myc1 = "" + obj[15];
				myc2 = "" + obj[16];
				xl1 = "" + obj[17];
				xl2 = "" + obj[18];
				
				boolean boo1 = compareNum(ssy1, ssy2, xr.getFssy());
				boolean boo2 = compareNum(szy1, szy2, xr.getFszy());
				boolean boo3 = compareNum(xl1, xl2, xr.getFxl());
				boolean boo4 = compareNum(myc1, myc2, xr.getFssy(), xr.getFszy());
				if(boo1 && boo2 && boo3 && boo4) {
					xr.setFstate_data("0");
				} else {
					xr.setFstate_data("1");
				}
			}
			xr_list.add(xr);
		}
		return xr_list;
	}
	
	
	private boolean compareNum(String v1, String v2, String str) {
		if(v1 == null || v1.equals("null") || v1.equals("")) {
			v1 = "0";
		}
		if(v2 == null || v2.equals("null") || v2.equals("")) {
			v2 = "0";
		}
		if(str == null || str.equals("null") || str.equals("")) {
			str = "0";
		}
		
		if(Double.parseDouble(v2) <= Double.parseDouble(str) && Double.parseDouble(str) <= Double.parseDouble(v1)) {
			return true;
		} else {
			return false;
		}
	}
	
	private boolean compareNum(String v1, String v2, String str1, String str2) {
		if(v1 == null || v1.equals("null") || v1.equals("")) {
			v1 = "0";
		}
		if(v2 == null || v2.equals("null") || v2.equals("")) {
			v2 = "0";
		}
		if(str1 == null || str1.equals("null") || str1.equals("")) {
			str1 = "0";
		}
		if(str2 == null || str2.equals("null") || str2.equals("")) {
			str2 = "0";
		}
		
		double dvl = Double.parseDouble(str1) - Double.parseDouble(str2);
		
		if(Double.parseDouble(v2) <= dvl && dvl <= Double.parseDouble(v1)) {
			return true;
		} else {
			return false;
		}
		
	}


	/**
	 * 
	* @Title: changePatientState 
	* @Description: 更新患者健康状态
	* @param @param fpid
	* @param @param fstate
	* @param @return 
	* @return boolean    返回类型 
	* @throws
	 */
	public boolean changePatientState(String fpid, String fstate) {
		try {
			String sql = "update tds_patient set fstate='" + fstate + "' " 
					   + " where fpid='" + fpid + "' and ftype='1' ";
			
			Query query = this.getSession().createSQLQuery(sql);
			int num = query.executeUpdate();
			if (num > 0) {
				return true;
			} else {
				return true;
			}

		} catch (RuntimeException re) {
			log.error("更新患者健康状态失败！", re);
			throw re;
		}
	}
	
	/**
	 * 
	* @Title: produceXyjRecordToChart 
	* @Description: 获取测量数据变化曲线 
	* @param @param fbtime
	* @param @param fetime
	* @param @param fphone1
	* @param @param fname
	* @param @return 
	* @return String    返回类型 
	* @throws
	 */
	public List<XyjRecord> produceXyjToChart(String fbtime, String fetime, String fphone1) {

		String sql = "";
		sql = " select frdate, fssy, fszy, fxl "
			+ " from tds_xyj_record  " 
			+ " where fphone='" + fphone1 + "' "; 
		
		if(fbtime == null || fbtime.equals("null") || fbtime.equals("")) {
			sql += " and frdate <= to_date('" + fetime + " 23:59:59','yyyy-mm-dd hh24:mi:ss') ";
		} else {
			sql += " and frdate between to_date('" + fbtime + " 00:00:00','yyyy-mm-dd hh24:mi:ss') and to_date('" + fetime + " 23:59:59','yyyy-mm-dd hh24:mi:ss') ";
		}
		
		sql	+= " order by frdate asc ";
		
		Query query = this.getSession().createSQLQuery(sql);
		List list = query.list();
		List<XyjRecord> xr_list = new ArrayList<XyjRecord>();
		
		int limit = 30;
		int total  = 0;
		int count  = 0;
		if(list != null) {
			total = list.size();
		}
		if(total <= limit) {
			count = 0;
		} else {
			count = total - limit;
		}
		
		for (int i = count; i < total; i++) {
				Object[] obj = (Object[]) list.get(i);
				XyjRecord xr = new XyjRecord();
				for (int j = 0; j < obj.length; j++) {
					xr.setFrdateStr("" + obj[0]);
					xr.setFssy("" + obj[1]);
					xr.setFszy("" + obj[2]);
					xr.setFxl("" + obj[3]);
				}
				xr_list.add(xr);
		}
		return xr_list;
	}
	
	/**
	 * 
	* @Title: produceXyjToChart 
	* @Description: 获取测量数据变化曲线 
	* @param @param fphone1
	* @param @return 
	* @return List<XyjRecord>    返回类型 
	* @throws
	 */
	public List<XyjRecord> produceXyjToChart(String fphone1, int limit) {

		String sql = "";
		sql = " select frdate, fssy, fszy, fxl "
			+ " from tds_xyj_record  " 
			+ " where fphone='" + fphone1 + "' "; 
		
		sql	+= " order by frdate asc ";
		
		Query query = this.getSession().createSQLQuery(sql);
		List list = query.list();
		List<XyjRecord> xr_list = new ArrayList<XyjRecord>();
		int total  = 0;
		int count  = 0;
		if(list != null) {
			total = list.size();
		}
		if(total <= limit) {
			count = 0;
		} else {
			count = total - limit;
		}
		
		for (int i = count; i < total; i++) {
				Object[] obj = (Object[]) list.get(i);
				XyjRecord xr = new XyjRecord();
				for (int j = 0; j < obj.length; j++) {
					xr.setFrdateStr("" + obj[0]);
					xr.setFssy("" + obj[1]);
					xr.setFszy("" + obj[2]);
					xr.setFxl("" + obj[3]);
				}
				xr_list.add(xr);
		}
		return xr_list;
	}
	
	public List<XtyRecord> produceXtyToChart(String fbtime, String fetime, String fphone1) {

		String sql = "";
		sql = " select frdate, fcqxt, fchxt1, fchxt2 "
			+ " from tds_xty_record  " 
			+ " where fphone='" + fphone1 + "' "; 
		
		if(fbtime == null || fbtime.equals("null") || fbtime.equals("")) {
			sql += " and frdate <= to_date('" + fetime + " 23:59:59','yyyy-mm-dd hh24:mi:ss') ";
		} else {
			sql += " and frdate between to_date('" + fbtime + " 00:00:00','yyyy-mm-dd hh24:mi:ss') and to_date('" + fetime + " 23:59:59','yyyy-mm-dd hh24:mi:ss') ";
		}
		
		sql	+= " order by frdate asc ";
		
		Query query = this.getSession().createSQLQuery(sql);
		List list = query.list();
		List<XtyRecord> xr_list = new ArrayList<XtyRecord>();
		
		for (int i = 0; i < list.size(); i++) {
			Object[] obj = (Object[]) list.get(i);
			XtyRecord xr = new XtyRecord();
			for (int j = 0; j < obj.length; j++) {
				xr.setFrdateStr("" + obj[0]);
				xr.setFcqxt("" + obj[1]);
				xr.setFchxt1("" + obj[2]);
				xr.setFchxt2("" + obj[3]);
			}
			xr_list.add(xr);
		}
		return xr_list;
	}
	
	
	/**
	 * 
	* @Title: signPatientRule 
	* @Description: 保存患者设置
	* @param @param pr
	* @param @return 
	* @return boolean    返回类型 
	* @throws
	 */
	public boolean signPatientRule(PatientRule pr) {
		try {
			getHibernateTemplate().saveOrUpdate(pr);
			getHibernateTemplate().flush();
			log.info("保存患者设置成功!");
			return true;
		} catch (DataAccessException e) {
			log.error("保存患者设置失败!");
			return false;
		}
	}

	/**
	 * 
	* @Title: saveXyjOfSetting 
	* @Description: 保存血压计设置信息 
	* @param @param fssy_low
	* @param @param fssy_high
	* @param @param fszy_low
	* @param @param fszy_high
	* @param @param fxl_low
	* @param @param fxl_high
	* @param @param fmyc_low
	* @param @param fmyc_high
	* @param @return 
	* @return String    返回类型 
	* @throws
	 */
	public boolean saveXyjOfSetting(String fphone, String fssy_low, String fssy_high, String fszy_low, String fszy_high, String fxl_low, String fxl_high, String fmyc_low, String fmyc_high) {
		try {
			DateUtils dateUtils = new DateUtils();
			String sql = "update tds_patient_setting set "
				       + "fssy_low='" + fssy_low + "' , "
				       + "fssy_high='" + fssy_high + "' , "
				       + "fszy_low='" + fszy_low + "' , "
				       + "fszy_high='" + fszy_high + "' , "
				       + "fxl_low='" + fxl_low + "' , "
				       + "fxl_high='" + fxl_high + "' , "
				       + "fmyc_low='" + fmyc_low + "' , "
				       + "fmyc_high='" + fmyc_high + "' , "
				       + "fopdate=" + " to_date('"
					   + dateUtils.getCurrentDateTime()
					   + "','YYYY-MM-DD HH24:MI:SS') "
					   + " where fphone='" + fphone + "' ";
			
			Query query = this.getSession().createSQLQuery(sql);
			int num = query.executeUpdate();
			if (num > 0) {
				log.info("保存血压计设置信息成功！");
				return true;
			} else {
				log.error("保存血压计设置信息失败！");
				return false;
			}

		} catch (RuntimeException re) {
			log.error("保存血压计设置信息失败！", re);
			throw re;
		}
	}

	/**
	 * 
	* @Title: getPatientSettingInfoByPhone 
	* @Description: 获取患者设置信息 
	* @param @param fphone
	* @param @return 
	* @return PatientSetting    返回类型 
	* @throws
	 */
	public PatientSetting getPatientSettingInfoByPhone(String fphone) {

		String sql = "";
		sql = " select fphone, fssy_low, fssy_high, fszy_low, fszy_high, fxl_low, fxl_high, fmyc_low, fmyc_high, "
			+ " fcqxt_low, fcqxt_high, fchxt1_low, fchxt1_high, fchxt2_low, fchxt2_high "
			+ " from tds_patient_setting " 
			+ " where fphone='" + fphone + "' "; 
		
		Query query = this.getSession().createSQLQuery(sql);
		List list = query.list();
		
		PatientSetting ps = new PatientSetting();
		if(list.size() <= 0) {
			return null;
		}
		for (int i = 0; i < list.size(); i++) {
			Object[] obj = (Object[]) list.get(i);
			for (int j = 0; j < obj.length; j++) {
				ps.setFssy_low("" + obj[1]);
				ps.setFssy_high("" + obj[2]);
				ps.setFszy_low("" + obj[3]);
				ps.setFszy_high("" + obj[4]);
				ps.setFxl_low("" + obj[5]);
				ps.setFxl_high("" + obj[6]);
				ps.setFmyc_low("" + obj[7]);
				ps.setFmyc_high("" + obj[8]);
				ps.setFcqxt_low("" + obj[9]);
				ps.setFcqxt_high("" + obj[10]);
				ps.setFchxt1_low("" + obj[11]);
				ps.setFchxt1_high("" + obj[12]);
				ps.setFchxt2_low("" + obj[13]);
				ps.setFchxt2_high("" + obj[14]);
			}
		}
		return ps;
	}
	
	
}
